package main

import (
	"github.com/google/wire"
	"google.golang.org/grpc"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
	"training-camp/week4/api/app1"
	pb "training-camp/week4/api/app1/v1"
	"training-camp/week4/config"
)

type App1 struct {
	cfg  *config.Config
	stop chan int
}

func (app *App1) Start() {

	appConfig, err := app.cfg.GetAppConfig("app1")
	if err != nil {
		log.Fatalf("get config err:%v", err)
		return
	}
	log.Printf("appconfig:%v", appConfig)
	listener, err := net.Listen("tcp", appConfig.Addr)
	if err != nil {
		log.Fatalf("net.listen err:%v", err)
	}
	log.Println(":8001", " net listening...")
	rpcServer := grpc.NewServer()
	pb.RegisterProdServiceServer(rpcServer, &app1.ProdService{})

	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		select {
		case <-sigs:
			log.Println("accept signal to cancel")
			rpcServer.Stop()
			app.Stop()
		}
	}()

	err = rpcServer.Serve(listener)
	if err != nil {
		log.Fatalf("grpc server err: %v", err)
	}
}
func (app *App1) Stop() {
	close(app.stop)
}
func NewApp1(cfg *config.Config) App1 {
	return App1{cfg: cfg}
}
func NewConfig(file string) *config.Config {
	return config.New(file)
}
func InitApp1(file string) App1 {
	wire.Build(NewConfig, NewApp1)
	return App1{}
}
func main() {

}
